package com.whj.wkpt.service;

import com.whj.wkpt.entity.Task;
import com.whj.wkpt.entity.User;
import com.whj.wkpt.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private TaskService taskService;

    public Optional<User> findByUsername(String username) {
        User user = userMapper.findByUsername(username);
        return user != null ? Optional.of(user) : Optional.empty();
    }

    public Optional<User> findByEmail(String email) {
        User user = userMapper.findByEmail(email);
        return user != null ? Optional.of(user) : Optional.empty();
    }

    public Optional<User> findById(Long userId) {
        User user = userMapper.findById(userId);
        return user != null ? Optional.of(user) : Optional.empty();
    }

    public boolean existsByUsername(String username) {
        return userMapper.existsByUsername(username);
    }

    public boolean existsByEmail(String email) {
        return userMapper.existsByEmail(email);
    }

    public User createUser(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
        return user;
    }
    
    public User save(User user) {
        return createUser(user);
    }

    public User updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
        return user;
    }

    public void deleteUser(Long userId) {
        // 先删除与该用户关联的所有任务（解决外键约束问题）
        List<Task> userTasks = taskService.findByEmployerId(userId);
        for (Task task : userTasks) {
            taskService.deleteTask(task.getTaskId());
        }
        
        // 然后删除用户
        userMapper.deleteById(userId);
    }

    public List<User> findAllUsers() {
        return userMapper.findAll();
    }
    
    public List<User> findByIds(List<Long> userIds) {
        // 处理空列表情况，避免SQL语法错误
        if (userIds == null || userIds.isEmpty()) {
            return new ArrayList<>();
        }
        return userMapper.findByIds(userIds);
    }
}